package cn.changeforyou.tcpIp.analysis.demo;

import cn.changeforyou.tcpIp.analysis.demo.protocol.gbt32960_3.BusUploadProtocol;
import cn.changeforyou.tcpIp.analysis.demo.protocol.gbt32960_3.enums.Command_Sign;
import cn.changeforyou.tcpIp.analysis.demo.protocol.gbt32960_3.Encryption_scheme;
import cn.changeforyou.tcpIp.analysis.demo.protocol.gbt32960_3.enums.Response_Sign;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import io.netty.util.AsciiString;
import java.nio.charset.Charset;
import java.util.List;
import org.apache.commons.codec.binary.Hex;

/**
 * @author zhyu
 * @date 2020/8/7 11:12
 */
public class CompleteDecoder extends ReplayingDecoder {

    CharSequence value;
    public static final AsciiString head = new AsciiString("2323");
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        CharSequence ascii = in.readCharSequence(4, Charset.forName("ASCII"));
        if(ascii.equals(head)) {
            BusUploadProtocol protocol = new BusUploadProtocol();
            CharSequence command_sign = in.readCharSequence(2, Charset.forName("ASCII"));
            CharSequence responseSign = in.readCharSequence(2, Charset.forName("ASCII"));
            protocol.setCommand_command_sign(Command_Sign.getByWord(command_sign));
            protocol.setCommand_response_sign(Response_Sign.getByWord(responseSign));
            CharSequence charSequence = in.readCharSequence(34, Charset.defaultCharset());
            String vin = new String(Hex.decodeHex((String) charSequence));
            protocol.setVin(vin);
            CharSequence encryption_scheme = in.readCharSequence(2, Charset.forName("ASCII"));
            protocol.setEncryption_scheme(Encryption_scheme.getByWord(encryption_scheme));
            short length = Short.parseShort((String) in.readCharSequence(4, Charset.defaultCharset()), 16);
            protocol.setData_unit_length(length);
            CharSequence data_charsequeue = in.readCharSequence(length * 2, Charset.defaultCharset());
            protocol.setDataUnitChars(((String)data_charsequeue).toCharArray());
            CharSequence bbc = in.readCharSequence(2, Charset.defaultCharset());
            protocol.setCheck_code((String) bbc);
            out.add(protocol);
        }
    }
}
